﻿using System.Diagnostics;

namespace WindowsFormsApp_consoleExec
{
    class CmdExecHelper
    {
        private ProcessStartInfo start_info = new ProcessStartInfo();
        private Process p = new Process();
        
        private CmdExecHelper()
        {

        }

        private void P_Exited(object sender, System.EventArgs e)
        {
            Started = false;
            Exited?.Invoke();
        }

        private void P_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            Received?.Invoke(e.Data);
        }

        private void P_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            ErrReceived?.Invoke(e.Data);
        }

        public delegate void CmdDataReceived(string s);
        public delegate void CmdExited();
        public event CmdDataReceived Received;
        public event CmdDataReceived ErrReceived;
        public event CmdExited Exited;

        public bool Started = false;

        public CmdExecHelper(string exec_path, string exec_args = null)
        {
            if(exec_args != null)
            {
                start_info.Arguments = exec_args;
            }
            start_info.RedirectStandardInput = true;
            start_info.RedirectStandardOutput = true;
            start_info.RedirectStandardError = false;
            start_info.UseShellExecute = false;
            start_info.FileName = exec_path;
        }

        public void Start()
        {
            if(!Started)
            {
                p.StartInfo = start_info;
                p.OutputDataReceived += P_OutputDataReceived;
                p.ErrorDataReceived += P_ErrorDataReceived;
                p.Exited += P_Exited;
                p.EnableRaisingEvents = true;
                Started = true;
                p.Start();
                p.BeginOutputReadLine();
            }
        }

        public void WriteLine(string s)
        {
            if(Started)
            {
                p.StandardInput.WriteLine(s);
            }
        }

        public void Abort()
        {
            if(Started)
            {
                Started = false;
                p.Close();
            }
        }
    }
}
